<template>
  <div class="card-page">
    <tool-bar nav="" :title="action_name + '应用部署设置服务器'" v-if="!$model || !$model.id">

      <el-button size="small" @click="clear_nexus_click" v-if="$props.action=='edit'">
        清理Nexus包
      </el-button>
      <el-button size="small" @click="$router.push('/dev/app-deploy-setting/add')" v-if="$props.action=='edit'">新建
      </el-button>
      <el-button size="small" @click="clone_click" v-if="$props.action=='edit'">克隆</el-button>
      <el-button size="small" @click="save_click" type="primary"> 保存</el-button>
    </tool-bar>
    <!--    <el-tag class="el-icon-warning">由于系统做了缓存,修改后,1分钟后生效!</el-tag>-->
    <el-row :gutter="12" type="flex">
      <el-col :span="12">
        <el-card shadow="always">
          <div v-if="info.isActive" class="current-set">
            当前
          </div>

          <kv label="当前配置（profile）">
            <el-input v-model="info.profile" chk="*"></el-input>
          </kv>

          <kv label="环境编码">
            <el-input v-model="info.code"
            />
          </kv>
          <kv label="环境名称">
            <el-input v-model="info.name"
            />
          </kv>

          <kv label="中台地址">
            <el-input v-model="info.mpIntegrationApiHost" chk="*"/>
          </kv>
          <kv label="admin-token">
            <el-input v-model="info.adminToken" chk="*"/>
          </kv>


          <kv label="备注">
            <el-input v-model="info.remark"/>
          </kv>

          <kv label="命名风格">
            <selector v-model="info.serviceNameStyle" enum="ServiceNameStyleEnum"/>
          </kv>
        </el-card>

        <jenkins-server v-model="info.jenkinsServer">
        </jenkins-server>


        <!--        <el-card>-->
        <!--          <kv>-->
        <!--            <template #k>-->
        <!--              <div class="k">Docker Api地址-->
        <!--                <remark> 如果不存在Jenkins，就使用 docker-api 进行构建！</remark>-->
        <!--              </div>-->
        <!--            </template>-->
        <!--            <el-input v-model="info.dockerApiUrl"/>-->
        <!--          </kv>-->
        <!--        </el-card>-->


        <fieldset>
          <legend>nexus</legend>


          <kv>
            <template #k>
              <div class="k">
                nexus私服域名
                <remark>构建时使用 <br/>
                  可以输入三种格式: http://xxx.com:8081 , //xxx.com:8081 , xxx.com:8081
                  <br/><br/>
                  maven 镜像地址：@nexusHost@/repository/maven-public/ <br/>
                  npm 镜像地址：@nexusHost@/repository/npm-group/ <br/>
                </remark>
              </div>
            </template>
            <el-input v-model="info.nexusServer.hostUrl"></el-input>
          </kv>
          <kv>
            <template #k>
              <div class="k">
                用户名,密码
                <remark>
                  部署jar包时使用，默认是 admin，如果不部署jar包，可以忽略
                </remark>
              </div>
            </template>
            <div style=" display: flex;justify-content: space-between;">
              <el-input v-model="info.nexusServer.userName"/>
              <el-input v-model="info.nexusServer.password"/>
            </div>
          </kv>

          <kv label="email">
            <el-input v-model="info.nexusServer.email"></el-input>
          </kv>
          <!--          <kv>-->
          <!--            <template #k>-->
          <!--              <div class="k">Maven镜像-->
          <!--                <remark>-->
          <!--                  构建时，设置为 mirrorOf=* 的地址，如果不填， 则使用上述私服 public 地址。-->
          <!--                </remark>-->
          <!--              </div>-->
          <!--            </template>-->
          <!--            <el-input v-model="info.mavenMirror"-->
          <!--                      placeholder="http://maven.aliyun.com/nexus/content/groups/public/"/>-->
          <!--          </kv>-->

          <kv label="snapshot Jar包策略">
            <selector v-model="info.snapshotVersionAction" enum="SnapshotVersionActionEnum"></selector>
          </kv>


        </fieldset>

        <fieldset>
          <legend>Harbor</legend>

          <harbor-server v-model="info.harborServer" v-if="info && info.harborServer">
          </harbor-server>
        </fieldset>
      </el-col>
      <el-col :span="12">

        <fieldset>
          <legend>页面</legend>

          <kv label="企业名称">
            <el-input v-model="info.corpName"/>
          </kv>

          <kv label="企业Logo">
            <el-input v-model="info.corpLogo"/>
          </kv>
          <kv label="icon">
            <el-input v-model="info.corpIcon"/>
          </kv>
          <kv label="系统名称">
            <el-input v-model="info.systemName"/>
          </kv>
          <kv label="登录页面">
            <el-input placeholder="login,login2,login3" v-model="info.loginPage"/>
          </kv>
        </fieldset>
        <el-card>
          <kv label="流水线">
            <selector v-model="info.pipelineTemplate" style="width:100%;" :enum-count="3"
                      enum="PipelineTemplateEnum" chk="*"
            ></selector>
          </kv>

        </el-card>

        <fieldset v-if="info.pipelineTemplate == 'K8s' ">
          <legend>K8s配置</legend>
          <k8s-config v-model="info.k8sConfig"/>
        </fieldset>

        <fieldset>
          <legend>Java设置</legend>


          <kv label="环境(mvn package -P)">
            <selector v-model="info.clusterDeployEnv" style="width:100%;"
                      :enum-count="5"
                      enum="MicroServiceDeployEnvEnum" chk="*"
            ></selector>
          </kv>

          <kv label="JavaOpts">
            <el-input v-model="info.javaOpts"/>
          </kv>
          <kv label="JavaArgs">
            <el-input v-model="info.javaArgs"/>
          </kv>

        </fieldset>

        <fieldset>
          <legend>前端打包</legend>


          <kv label="前端打包工具">
            <selector v-model="info.packageTool" :data="['Npm','Yarn']"></selector>
          </kv>

          <kv label="移除 npm lock">
            <el-switch
                v-model="info.removeNpmLock">
            </el-switch>
          </kv>
        </fieldset>


        <fieldset>
          <legend>Docker 构建时 --add-host</legend>


          <input-table style="width:100%"
                       v-model="info.dockerBuildHosts">
            <el-table-column align="center" label="域名" minWidth="120">
              <template v-slot="scope">
                <el-input v-model="scope.row.host" chk="*" style="width:100%"/>
              </template>
            </el-table-column>
            <el-table-column align="center" label="IP" minWidth="80">
              <template v-slot="scope">
                <el-input v-model="scope.row.ip" chk="*"/>
              </template>
            </el-table-column>
          </input-table>

        </fieldset>

      </el-col>
    </el-row>

    <el-card style="background-color: #4da6a6">
      <k8s-language v-model="info.languageSettings"></k8s-language>
    </el-card>


  </div>
</template>
<style lang="scss" scoped>
.space-between {
  display: flex;
  justify-content: space-between;
}

.current-set {
  position: absolute;
  left: 12px;
  top: 7px;
  background-color: rgb(142 41 142);
  color: white;
  font-size: larger;
  border-radius: 8px;
  padding: 3px 6px;
}


::v-deep(.el-table) {
  .btns {
    button {
      padding: 7px 10px !important;
    }
  }
}

.el-button + .el-button {
  margin-left: 4px;
}
</style>
<script setup>
/**
 * Created by CodeGenerator  at 2022-04-29 15:19:56
 */
import jenkinsServer from "./jenkins-server-card.vue"
import harborServer from "./harbor-server-card.vue"
import k8sConfig from "./k8s-config-card.vue"
import k8sLanguage from "./k8s-language-config.vue"

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();


//定义data
const $data = reactive({
  dlg_show: false,
  dlg_row: {},
  dlg_field: "",
  dlg_input: "",
  servers: {'': '默认', 'tong': '东方通'},
  view_dockerfile_dlg: false,
  dockerfile: "",
  info: {
    sshServer: {},
    pipelineTemplate: "",
    nginxServerPort: 800,
    jenkinsServer: {},
    k8sConfig: {},
    msConfig: {},
    nexusServer: {},
    dockerBuildHosts: [],
    languageSettings: [],
  }, //子对象需要声明。
});

const info = $computed(() => $data.info);

const $props = defineProps({
  action: {type: String},
  id: {type: String}
});

const $model = defineModel({type: Object});


const list = ref();

//定义事件
const $emit = defineEmits(["update:modelValue", "loaded"]);


const action_name = $computed(function () {
  return {add: "添加", edit: "修改", view: "查看"}[$props.action]
});
const isView = $props.action == "view";

const instance = getCurrentInstance()

const setViewMode = function () {
  nextTick(() => {
    var i = 0;

    function findAllComponents(vnode, callback) {


      function traverse(vnode) {
        if (vnode.component) {
          // 是组件节点，记录它的组件实例
          if (callback(vnode.component) == false) {
            return;
          }
        } else {
          i++;
        }

        // 遍历直接子节点
        if (vnode.children && vnode.children.forEach) {
          vnode.children.forEach(child => {
            if (typeof child !== 'string' && child.type) {
              // 如果是组件或元素，继续遍历
              traverse(child)
            }
          })
        }

        // 如果是组件，还要递归遍历它的 subTree
        if (vnode.component) {
          traverse(vnode.component.subTree)
        }
      }

      traverse(vnode)
      return
    }

    var map = new Set();
    findAllComponents(instance.subTree, it => {
      var tag = it.type.name;
      if (!tag) {
        return;
      }
      map.add(tag);
      if (tag == "ElButton") {
        it.vnode.el.style.display = "none";
      }
      if (tag.IsIn("ElInput", "ElSelect", "ElSwitch", "selector")) {

        it.props.disabled = true;
        it.props.readOnly = true;
        if (tag == "ElInput") {
          Array.from(it.vnode.el.querySelectorAll("input")).forEach(item => {
            item.placeholder = "";
          })
        }

        if (tag == "selector") {
          return;
        }
        return false;
      }

    })

    console.log("tags: " + Array.from(map).join(","))
  })
}


const loadData = async function () {
  if (!$props.id) return;
  var res = await jv.$http.post("/dev/app-deploy-setting/detail/" + $props.id)
  $data.info = res.data.data;

  if (isView) {
    setViewMode();
  }
};
const save_click = async function () {
//校验
  if (jv.chk_main($data) == false) {
    return;
  }
  var res = await jv.$http.post("/dev/app-deploy-setting/save", $data.info)
//[axios拦截器中已处理了异常]。
  jv.info(action_name + " 成功");
  var id = res.data.data || $data.info.id;
  if (id) {
    jv.$router.push("/dev/app-deploy-setting/edit/" + id);
  }
};

const clone_click = async function () {
  $data.info.id = "";
  $data.info.code = $data.info.code + "-clone"
  $data.info.isActive = false;
  save_click();
};


const clear_nexus_click = function () {
  jv.prompt("保留最近几个版本").then(res => {
    var number = res.value;
    if (!number) {
      return;
    }

    jv.$http.post("/dev/app-deploy-setting/clear-nexus?id=" + $props.id + "&number=" + number).then(res => {
      jv.alert("清理完成");
    })
  })
}

onMounted(function () {
// this.integration_host = jv.getFullUrl(jv.SERVER_INTEGRATION_HOST);
  loadData();
})


</script>
